<template>
  <header class="header">
    <div class="header_content">
      <div class="header_left">
        <a class="header_logo" href="#screen_1" @click.prevent="handleLogoClick">
          <img class="svg" src="@/assets/images/logo.svg" alt="Sangyie">
        </a>
      </div>
      <div class="header_right">
        <ul class="nav_list" :class="{ 'active': isMenuOpen }">
          <NavItem
            v-for="item in navItems" 
            :key="item.id"
            :id="item.id"
            :text="item.text"
            :path="item.path"
            :anchor="item.anchor"
            @navigate="scrollToSection"
          />
        </ul>
        <a 
          class="header_links_trigger" 
          :class="{ 'opened': isMenuOpen }"
          @click.prevent="toggleMenu"
          aria-label="Toggle navigation menu"
        >
          <span></span>
          <span></span>
          <span></span>
        </a>
      </div>
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavItem from './NavItem.vue'

// 为全局scrollToSection方法声明类型
declare global {
  interface Window {
    scrollToSection?: (sectionId: string) => boolean | void;
    currentSectionId?: string; // 添加全局当前section ID
  }
}

interface NavItemType {
  id: number
  text: string
  path: string
  anchor?: string // 锚点属性，用于页面内导航
}

const router = useRouter()
const route = useRoute()

const navItems: NavItemType[] = [
  { id: 1, text: '首页', path: '/', anchor: 'home' },
  { id: 2, text: '关于公司', path: '/', anchor: 'about' },
  { id: 3, text: '目录', path: '/products', anchor: 'catalog' },
  { id: 4, text: '服务', path: '/', anchor: 'services' },
  { id: 5, text: '合作伙伴', path: '/', anchor: 'partners' },
  { id: 6, text: '客户', path: '/', anchor: 'clients' },
  { id: 7, text: '联系方式', path: '/', anchor: 'contact' }
]

const isMenuOpen = ref(false)

// 平滑滚动到指定section
const scrollToSection = (sectionId?: string) => {
  // 关闭移动端菜单
  closeMobileMenu()
  
  // 如果没有指定section，则不处理
  if (!sectionId) return
  
  // 检查是否存在全局滚动方法（由test.vue提供）
  if (window.scrollToSection) {
    // 使用test.vue提供的滚动方法
    window.scrollToSection(sectionId)
    return
  }
  
  // 如果没有全局滚动方法，则使用默认滚动行为
  const targetElement = document.getElementById(sectionId)
  
  // 如果找到目标元素，则滚动到该位置
  if (targetElement) {
    // 计算目标位置，考虑导航栏高度
    const navHeight = 70
    const targetPosition = targetElement.getBoundingClientRect().top + window.scrollY - navHeight
    
    // 使用平滑滚动
    window.scrollTo({
      top: targetPosition,
      behavior: 'smooth'
    })
    
    // 更新URL哈希值，但不触发滚动
    history.pushState(null, '', `#${sectionId}`)
  }
}

const toggleMenu = () => {
  isMenuOpen.value = !isMenuOpen.value
}

const closeMobileMenu = () => {
  isMenuOpen.value = false
}

// 处理Logo点击
const handleLogoClick = () => {
  // 关闭移动端菜单
  closeMobileMenu()
  
  // 检查当前是否在主页
  if (route.path !== '/') {
    // 如果不在主页，先导航到主页，然后滚动到首页section
    document.body.style.overflow = 'hidden' // 恢复主页的滚动设置
    router.push('/').then(() => {
      setTimeout(() => {
        if (window.scrollToSection) {
          window.scrollToSection('home')
        }
      }, 100)
    })
  } else {
    // 如果已经在主页，直接滚动到首页section
    scrollToSection('home')
  }
}

// 处理URL哈希变化
const handleHashChange = () => {
  const hash = window.location.hash.substring(1)
  if (hash) {
    scrollToSection(hash)
  }
}

// 添加触摸事件支持
const initTouchEvents = () => {
  // 获取导航菜单元素
  const navMenu = document.querySelector('.nav-menu')
  if (!navMenu) return
  
  let touchStartX = 0
  let touchEndX = 0
  
  // 添加触摸开始事件
  navMenu.addEventListener('touchstart', (e) => {
    const event = e as TouchEvent
    touchStartX = event.changedTouches[0].screenX
  }, { passive: true })
  
  // 添加触摸结束事件
  navMenu.addEventListener('touchend', (e) => {
    const event = e as TouchEvent
    touchEndX = event.changedTouches[0].screenX
    
    // 向左滑动关闭菜单
    if (touchEndX < touchStartX - 50 && isMenuOpen.value) {
      closeMobileMenu()
    }
  }, { passive: true })
}

onMounted(() => {
  // 添加哈希变化事件监听
  window.addEventListener('hashchange', handleHashChange)
  
  // 初始化触摸事件
  initTouchEvents()
  
  // 如果URL中包含哈希值，则滚动到对应位置
  if (window.location.hash) {
    const hash = window.location.hash.substring(1)
    setTimeout(() => scrollToSection(hash), 700)
  }
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('hashchange', handleHashChange)
})
</script>

<style scoped>
/* 样式已在全局 aftech-styles.css 中定义 */
/* 组件特定样式可以在这里添加 */
</style>